package lc.smart.android.net;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import lc.smart.android.helper.BaseConfigHelper;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;

/**
 * 常用的网络访问或网络处理方法类
 * @author Smart lichong_951@163.com
 * 
 * */
public class MyNetWork
{
	private Context context;
	private static MyNetWork myNetWork;

	/**
	 * 使用单例模式获取唯一的网络访问对象
	 *@param context 上下文
	 *@return 返回一个实例对象
	 * */
	public static MyNetWork getInstance(Context context)
	{
		if (myNetWork == null)
		{
			myNetWork = new MyNetWork(context);
		}
		return myNetWork;
	}

	public MyNetWork(Context context)
	{
		this.context = context;
	}

	/**
	 * 检查网络环境
	 *@param context 上下文资源
	 * 
	 *@return null ： 没有网络环境 ； 2GOR3G：移动网络；   WIFI：WIFI网络环境。
	 * */
	public static String isNetworkAvailable(Context context)
	{
		//Log.i(TAG, "----------------------isNetworkAvailable called!");
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm == null)
		{
			return null;
		}
		else
		{
			NetworkInfo networkINfo = cm.getActiveNetworkInfo();
			if (networkINfo != null
					&& networkINfo.getType() == ConnectivityManager.TYPE_MOBILE)
			{
				return "2GOR3G";
			}
			else if (networkINfo.getType() == ConnectivityManager.TYPE_WIFI)
			{
				return "WIFI";
			}
			else
			{
				return null;
			}
		}
	}

	/**
	 * 获取get方式的网络连接
	 * */
	public HttpURLConnection getConn(URL url, Handler handler)
	{
		try
		{
			HttpURLConnection getConnection = (HttpURLConnection) url
					.openConnection();
			getConnection.setDoInput(true);
			getConnection.setDoOutput(true);
			getConnection.setUseCaches(false);
			getConnection.setRequestMethod("GET");
			//getConnection.set

			return getConnection;
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			Message msg = new Message();
			msg.what = BaseConfigHelper.Msg_Service_Disable;
			handler.sendMessage(msg);

		}
		return null;
	}

	/**
	 * 获取post方式的网络连接
	 * */

}
